package com.czb.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czb.seckill.exception.GlobalException;
import com.czb.seckill.mapper.UserMapper;
import com.czb.seckill.pojo.User;
import com.czb.seckill.service.UserService;
import com.czb.seckill.util.CookieUtil;
import com.czb.seckill.util.MD5Util;
import com.czb.seckill.util.UUIDUtil;
import com.czb.seckill.util.ValidatorUtil;
import com.czb.seckill.vo.LoginVo;
import com.czb.seckill.vo.RespBean;
import com.czb.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 陈正彬
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    //配置RedisTemplate，操作redis
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest httpServletRequest,
                            HttpServletResponse httpServletResponse) {
        //接收mobile和password（midPassword）
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //判断
//        if (!StringUtils.hasText(mobile) || !StringUtils.hasText(password)) {
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
        //判断手机号码是否合格
//        if (!ValidatorUtil.isMobile(mobile)) {
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }
        //查询DB，用户是否存在
        User user = userMapper.selectById(mobile);
        if (null == user){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            //使用全局异常
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        if (!MD5Util.midPassToDBPass(password,user.getSlat()).equals(user.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //登入成功

        //给每个用户生成一个票据
        String ticket = UUIDUtil.uuid();
        //将登入成功的用户保存到session
        //httpServletRequest.getSession().setAttribute(ticket,user);
        //为了实现分布式session，把登入的用户存放到Redis
        redisTemplate.opsForValue().set("user:"+ticket,user);
        //将ticket保存到cookie
        CookieUtil.setCookie(httpServletRequest,httpServletResponse,
                "userTicket",ticket);
        //返回userTicket
        return RespBean.success(ticket);
    }

    //根据cookie-ticket,获取用户的信息
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request,
                                HttpServletResponse response) {

        if (!StringUtils.hasText(userTicket)){
            return null;
        }
        //根据ticket，到redis获取User
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        //如果用户不为null，就重新设置cookie（刷新）
        if (user != null) {
            CookieUtil.setCookie(request,response,"userTicket",userTicket);

        }

        return user;
    }

    //更新密码，解决redis缓存与DB数据不一致问题
    @Override
    public RespBean updatePassword(String userTicket,String password,HttpServletRequest request,
                                   HttpServletResponse response) {

        User user = getUserByCookie(userTicket, request, response);
        if (user == null){
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        //设置新密码
        user.setPassword(MD5Util.inputPassToDBPass(password,user.getSlat()));
        int update = userMapper.updateById(user);
        if (update == 1 ){//更新成功
            redisTemplate.delete("user:"+ userTicket);
            return RespBean.success();
        }

        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }
}
